<?php

include_once("playlist.class.php");
include_once("operacionesBD.php");

class PlaylistMapper
{
    public static function findById($id) {
        $dbh = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "SELECT * from playlists WHERE playlistid = '$id'";
        $data = $dbh->consultar($query);
        if (!$data) return false;
        return new Playlist($id, $data[0]['name'], $data[0]['xml'], $data[0]['userid']);
    }
    
    public static function findByUserid($userid) {
        $dbh = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "SELECT * from playlists WHERE userid = '$userid'";
        $data = $dbh->consultar($query);
        if (!$data) return false;
        else {
            foreach($data as $d) {
                $playlists[] = new Playlist($d['playlistid'], $d['name'], $d['xml'], $userid);
            }
        }
        return $playlists;
    }
    
    public static function findByUseridAndName($userid, $name) {
        $dbh = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "SELECT * from playlists WHERE userid = '$userid' AND name = '$name'";
        $data = $dbh->consultar($query);
        if (!$data) return false;
        else {
            foreach($data as $d) {
                $playlists[] = new Playlist($d['playlistid'], $name, $d['xml'], $userid);
            }
        }
        return $playlists;
    }
    
    public static function findAllPlaylists() {
        $dbh = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "SELECT * from playlists";
        $data = $dbh->consultar($query);
        if (!$data) return false;
        else {
            foreach($data as $d) {
                $playlists[] = new Playlist($d['playlistid'], $d['name'], $d['xml'], $d['userid']);
            }
        }
        return $playlists;
    }

    public function update(Playlist $playlist) {
        $dbh = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "UPDATE playlists SET playlistid = '{$playlist->get_id()}', name = '{$playlist->get_name()}', xml = '{$playlist->get_xml()}' WHERE userid = '{$playlist->get_userid()}'";
        $data = $dbh->modificar($query);
    }

    public function insert(Playlist $playlist) {
        $dbh = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "INSERT INTO playlists VALUES ('{$playlist->get_id()}', '{$playlist->get_name()}', '{$playlist->get_xml()}', '{$playlist->get_userid()}')";
        $id = $dbh->modificar($query);
	return $id;
    }

    public function delete(Playlist $playlist) {
        $dbh = operacionesBD::getInstance('localhost', 'root', '', 'musica');
        $query = "DELETE FROM playlists WHERE playlistid = '{$playlist->get_id()}'";
        $data = $dbh->modificar($query);
    }
    
}

?>
